#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "ao_rw.h"
#include "ao_test.h"
#include "thread_ctrl.h"
#include "ietAoLib.h"

/* 发送线程函数 */
void *send_ao_thread(void *arg)
{
    struct ao_dev_t *pdev = (struct ao_dev_t *)arg;
    struct ao_param_t *pparam = (struct ao_param_t *)pdev->parent;
    struct thread_param_t *pthread = pdev->write_thread;
    int ret = 0;
    int i = 0;

    /* 检查参数是否有效 */
    if (!pthread || !pthread->name) {
        fprintf(stderr, "Invalid parameters for %s\n", __func__);
        return NULL;
    }

    /* 线程取消 SIGUSR1 的阻塞 */
    init_thread_user_signal();
    // printf("Start %s send thread...\n", pdev->path);
    while (!pthread->exit_sig) {
        for (i = 0; (pparam->write_cnt == -1 || i < pparam->write_cnt) && !pthread->exit_sig; i++) {
            ret = AOMWriteReal(pdev->index, pdev->set_val);
            if (ret < 0) {
                fprintf(stderr, "AOMWriteReal AO %2d current %.6lfmA failed\n", pdev->index, pdev->set_val);
                return NULL;
            }
            printf("AOMWriteReal AO %2d current %.6lfmA\n", pdev->index, pdev->set_val);
            break;
        }
        // printf("Write %s %d data done\n", pdev->path, pparam->write_cnt);
        break;
    }
    // printf("%s %s return\n", pdev->path, __func__);

    return NULL;
}
